package com.meisupic.copyright.controller;

import com.alibaba.fastjson.JSON;
import com.meisupic.copyright.common.PayWayEnum;
import com.meisupic.copyright.domain.bo.RCodeUpdateBo;
import com.meisupic.copyright.domain.vo.ReturnToDciMessageVo;
import com.meisupic.copyright.service.ICopyRightWorksService;
import com.meisupic.copyright.service.IWeiXinPayService;
import com.meisupic.copyright.util.StringUtil;
import com.meisupic.copyright.util.WeiXinPayUtils;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author lanjian
 * @Date 2018/3/12 下午3:22
 */
@RestController
@RequestMapping("/notify")
public class NotifyController {

  @Autowired
  ICopyRightWorksService copyRightWorksService;

  @Autowired
  IWeiXinPayService weiXinPayService;

  @Autowired
  protected HttpServletRequest request;

  @Autowired
  protected HttpServletResponse response;

  @RequestMapping("/receiveDciertificate")
  public String receiveDciertificate(String callbackMessage) {
    ReturnToDciMessageVo returnToDciMessageVo = copyRightWorksService
        .receiveDciCertificate(callbackMessage);
    return JSON.toJSONString(returnToDciMessageVo);
  }

  @RequestMapping("receiveContractRecordResult")
  public String receiveContractRecordResult(String callbackMessage) {

    return null;
  }

  @RequestMapping("updateRCodeInfo")
  public String updateRCodeInfo(@RequestBody RCodeUpdateBo rCodeUpdateBo) {
    return copyRightWorksService.updateRCodeStatus(rCodeUpdateBo);
  }

  @RequestMapping("/scanPay/{payWayCode}")
  public void notify(@PathVariable("payWayCode") String payWayCode) throws Exception {
    Map<String, String> notifyMap = new HashMap<String, String>();
    if (PayWayEnum.WEIXIN.name().equals(payWayCode)) {
      InputStream inputStream = request.getInputStream();// 从request中取得输入流
      notifyMap = WeiXinPayUtils.parseXml(inputStream);
    }
    String completeWeiXinScanPay = weiXinPayService.completeScanPay(payWayCode, notifyMap);
    if (!StringUtil.isEmpty(completeWeiXinScanPay)) {
      if (PayWayEnum.WEIXIN.name().equals(payWayCode)) {
        response.setContentType("text/xml");
      }
      response.getWriter().print(completeWeiXinScanPay);
    }
  }
}
